import os
import sys
import glob
from distutils.core import setup, Extension
from distutils.command.clean import clean
from distutils.command.install import install
from distutils.file_util import copy_file

try:
    # For some reason, importing Pyrex appears to change the value of
    # the MACOSX_DEPLOYMENT_TARGET to something that may be
    # inaccurate.  So we'll make sure that it's set to whatever it was
    # before we imported Pyrex.
    oldTarget = os.environ.get("MACOSX_DEPLOYMENT_TARGET", "")

    from Pyrex.Distutils import build_ext

    os.environ["MACOSX_DEPLOYMENT_TARGET"] = oldTarget

    sources = ["honeyjs.pyx"]
except ImportError:
    print "You don't seem to have Pyrex installed. Please install it."
    sys.exit(1)

jslibdir = "/usr/local/lib/"
emulibdir = "/opt/libemu/lib/libemu/"
jsincdir = "/usr/include/smjs/"
emuincdir = "/opt/libemu/include/"

class honeyjs_install(install):
    def run(self):
        install_dir = glob.glob(os.path.join("build","lib.*"))[0]
        copy_file(os.path.join(install_dir,"honeyjs.so"),
                  "./")

class honeyjs_build_ext(build_ext):
    def run(self):

        self.include_dirs.extend([jsincdir, jslibdir])
        self.include_dirs.extend([emuincdir, emulibdir])
        self.library_dirs.append(jslibdir)
        self.library_dirs.append(emulibdir)

        if self.define is None:
            self.define = []
        self.define.append(("XP_UNIX", None))

        build_ext.run(self)

setup(name = "honeyjs",
      version = "0.0.1",
      license = "GPL",
      author = "Z Chen John J. Lee",
      author_email = "imzchen@gmail.com",
      description = "JavaScript / Python bridge with Malware Detection",
      url = "http://code.google.com/p/phoneyc/",
      long_description = """\
The honeyjs module is derived from python-spidermonkey project ( by 
John J. Lee, jjl@pobox.com, http://code.google.com/p/python-spidermonkey/).
The following is the project description of python-spidermonkey:
Python/JavaScript bridge module, making use of Mozilla's spidermonkey
JavaScript implementation.  Allows implementation of JavaScript classes,
objects and functions in Python, and evaluation and calling of JavaScript
scripts and functions respectively.  Borrows heavily from Claes Jacobssen's
Javascript Perl module, in turn based on Mozilla's 'PerlConnect' Perl binding.
""",
      ext_modules =  [Extension("honeyjs",
                                sources=sources,
                                libraries=["js", "stdc++","emu"])],
      cmdclass = {'build_ext': honeyjs_build_ext,
                  'install':honeyjs_install}
      )
